<template>
  <a-spin v-if="currentGroup" :spinning="loading" class="pv16 pr16">
    <div class="flex-center-between">
      <SelectCompany :hasLeftIcon="true" :selectTreeId.sync="subjectId" :type.sync="subjectType" />
      <a-button :disabled="(currentGroup && currentGroup.level === 1) || !currentGroup" type="primary" @click="goAdd">添加政策</a-button>
    </div>
    <div class="flex-center mt16">
      <a-input-search
        v-model="searchTitle"
        allowClear
        placeholder="请输入政策标题"
        class="mr16"
        style="width: 200px"
        @change="onSearchTitleChange"
      />
      <a-select
        v-model="searchPolicyLevel"
        :options="levelOptions"
        allowClear
        placeholder="请选择政策级别"
        style="width: 200px"
        @change="onSearchPolicyLevelChange"
      />
    </div>
    <div class="mt24">
      <a-table
        :dataSource="dataSource"
        :columns="columns"
        :pagination="pagination"
        :customRow="customRow"
        rowKey="id"
        @change="handleTableChange"
      >
        <template slot="policyLevel" slot-scope="text">
          <a-tooltip :title="levelOptionsDict[text].label">
            {{ levelOptionsDict[text].label }}
          </a-tooltip>
        </template>
        <template slot="companyTypeList" slot-scope="text">
          <a-tooltip v-if="text" :title="text.map((li) => li.name).join('，')" placement="topLeft">
            {{ text[0].name }} 等 {{ text.length }} 个
          </a-tooltip>
          <span v-else></span>
        </template>
        <template slot="title_slot" slot-scope="text">
          <a-tooltip :title="text" placement="topLeft">
            {{ text }}
          </a-tooltip>
        </template>
        <template slot="annex" slot-scope="text">
          <a-tooltip v-if="text" :title="annexTip(text)" placement="topLeft">
            {{ annexText(text) }}
          </a-tooltip>
          <span v-else></span>
        </template>
        <template slot="createTime" slot-scope="text">
          {{ $dayjs(text).format("YYYY-MM-DD") }}
        </template>
        <template slot="action" slot-scope="text, record">
          <a-space>
            <span class="tc-theme pointer" @click="goEdit(record, 'detail')">详情</span>
            <span class="tc-theme pointer" @click="goEdit(record)">编辑</span>
            <a-popconfirm title="确认要删除吗？" @confirm="doDelete(record.id)">
              <span class="tc-theme pointer">删除</span>
            </a-popconfirm>
            <a-icon class="move" type="drag" />
          </a-space>
        </template>
      </a-table>
    </div>
  </a-spin>
</template>
<script>
import { columns, levelOptions, levelOptionsDict } from "./funcs";
import SelectCompany from "@/components/SelectCompany";
import _ from "lodash";
import { getFileName } from "@/utils/tools";
export default {
  name: "",
  components: { SelectCompany },
  mixins: [],
  props: {
    currentGroup: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      levelOptions,
      levelOptionsDict,
      columns,
      dataSource: [],
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ["10", "20", "50", "100"]
      },
      subjectId: "-1",
      subjectType: "site",
      searchPolicyLevel: undefined,
      searchTitle: "",
      loading: false,
      dragSource: null,
      dragTarget: null
    };
  },
  computed: {},
  watch: {
    subjectId() {
      this.pagination.current = 1;
      this.onSearchChange();
    },
    currentGroup: {
      handler() {
        this.pagination.current = 1;
        this.onSearchChange();
      },
      deep: true
    }
  },
  created() {},
  mounted() {},
  methods: {
    customRow(record) {
      return {
        props: {},
        style: {
          cursor: "pointer"
        },
        on: {
          mouseenter: (event) => {
            const evt = event || window.event;
            evt.target.draggable = true;
          },
          dragstart: (event) => {
            const evt = event || window.event;
            evt.stopPropagation();
            this.dragSource = record;
          },
          dragover: (event) => {
            const evt = event || window.event;
            evt.preventDefault();
          },
          drop: (event) => {
            const evt = event || window.event;
            evt.stopPropagation();
            this.dragTarget = record;
            this.$request({
              url: `/hr/api/v1/policyCouriers/updateSort`,
              method: "put",
              data: [
                { id: this.dragSource.id, sort: this.dragTarget.sort },
                { id: this.dragTarget.id, sort: this.dragSource.sort }
              ]
            })
              .then(() => {
                this.onSearchChange();
              })
              .catch(() => {});
          }
        }
      };
    },
    annexTip(t) {
      return t
        .split(",")
        .map((url) => getFileName(url, true))
        .join("，");
    },
    annexText(t) {
      const urls = t.split(",");
      return getFileName(urls[0], true) + `等 ${urls.length} 个`;
    },
    onSearchTitleChange: _.throttle(function () {
      this.pagination.current = 1;
      this.onSearchChange();
    }, 1000),
    onSearchPolicyLevelChange() {
      this.pagination.current = 1;
      this.onSearchChange();
    },
    goEdit(record, page) {
      localStorage.setItem("tempZhengce", JSON.stringify(record));
      if (page === "detail") {
        this.$router.push(`/admin/zhengcesudi/detail?id=${record.id}&tId=${this.currentGroup.code}`);
      } else {
        this.$router.push(`/admin/zhengcesudi/edit?id=${record.id}&tId=${this.currentGroup.code}`);
      }
    },
    goAdd() {
      this.$router.push(`/admin/zhengcesudi/edit?tId=${this.currentGroup.code}`);
    },
    doDelete(policyCourierId) {
      this.$request({
        url: `/hr/api/v1/policyCouriers/${policyCourierId}`,
        method: "delete"
      })
        .then((res) => {
          this.$message.success("已删除");
          this.onSearchChange();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.onSearchChange();
    },
    onSearchChange() {
      if (this.loading) {
        return false;
      }
      this.loading = true;
      const reqData = {
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
        typeCode: this.currentGroup.code,
        TypeAndId: {
          id: this.subjectId,
          type: this.subjectType
        }
      };
      if (this.searchPolicyLevel) {
        reqData["policyLevel"] = this.searchPolicyLevel;
      }
      if (this.searchTitle) {
        reqData["title"] = this.searchTitle;
      }
      this.$request({
        url: `/hr/api/v1/policyCouriers/selectPage`,
        method: "post",
        data: reqData
      })
        .then((res) => {
          this.dataSource = res.data.entities;
          this.pagination.total = res.data.entityCount;
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });
    }
  }
};
</script>
<style lang="scss"></style>
